package com.ls.gateway.filter;//package com.mall.gateway.filter;

import com.ls.common.exception.BusinessException;
import com.ls.common.util.JwtUtil;
import com.ls.common.util.ResponeUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Description
 * @Author konglz
 * @Data 2023/4/27 15:23
 */
@Component
@Order(1)
@Slf4j
public class LoginFilter implements GlobalFilter {

    @Autowired
    StringRedisTemplate redisTemplate;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //配置白名单
        if(exchange.getRequest().getPath().toString().contains("/user/login")){
            return chain.filter(exchange);
        }

        //1、获取token
        ServerHttpRequest request = exchange.getRequest();
        String token = request.getHeaders().getFirst("token");
//        ServerHttpResponse response = exchange.getResponse();

        //2、判断前端传过来的token是否为空
        if(token == null){
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        //3、判断redis中是否存在token
        String redisToken = redisTemplate.opsForValue().get("mall-parent:login:" + token);
        if(redisToken == null){
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }

        //4、判断token是否过期，过期也报401
        try {
            Claims claims = JwtUtil.parseJWT(token);
            if(claims.get("username") == null){
                log.error("token过期,username为null");
                exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
                return exchange.getResponse().setComplete();
            }
        } catch (Exception e) {
//            e.printStackTrace();

//            DataBuffer buffer = ResponeUtils.getResponeBuffer(response);
//            return response.writeWith(Mono.just(buffer));
            throw new BusinessException(HttpStatus.UNAUTHORIZED.value(), "未认证");
//            throw new RuntimeException("header中的token有问题",e);
        }

        return chain.filter(exchange);
    }
}
